/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package akheer.smsc;

import akheer.safe.*;
import akheer.safe.net.RabbitClient;
import akheer.safe.net.RabbitClientMessage;
import akheer.safe.net.RabbitClientMessageType;

import java.io.*;
import java.util.*;
import java.text.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Saad
 */
public class SMSC implements Observer {

    private static final Logger log = LoggerFactory.getLogger("SMSC");
            
    private RabbitClient rc;
    
    private HashMap<String, SMS> storeSMS;
    
    private SMSC(String host) throws IOException {
        
        rc = new RabbitClient(host, "SMSC", "smscIN", "smscIN");
        
        storeSMS = new HashMap<String, SMS>();
    }
    
    public void start() {
        
        rc.addObserver(this);
        rc.startListening("smscIN", true);
    }
    
    public void stop() {
        
        rc.stopListening();
    }
    
    @Override
    public void update(Observable o, Object arg) {
        
        try {
            
            RabbitClientMessage rcmIn = new RabbitClientMessage(arg.toString());
            String message = rcmIn.getMessage();
            
            switch(rcmIn.rcmt)
            {
                case SMS_NEW:
                {
                    SMS sms = new SMS(message);
                    
                    if ( sms.getTextMessage().contains("echo") ) {
                        
                        sms.setRecievingNumber(sms.getSendingNumber());
                        
                        RabbitClientMessage rcmOut = new RabbitClientMessage();
                        rcmOut.setMessageType(RabbitClientMessageType.SMS_SEND);
                        rcmOut.setMessage(sms.toString());
                        rc.sendMessage("FS", "fsIN", rcmOut);
                    }
                    else if ( sms.getTextMessage().length() > 12 ) {
                        
                        sms.setRecievingNumber(sms.getSendingNumber());
                        sms.setMessageText("Invalid data. Alpha-Numeric characters of length 12 allowed. Input example: ab0123456789");
                    
                        RabbitClientMessage rcmOut = new RabbitClientMessage();
                        rcmOut.setMessageType(RabbitClientMessageType.SMS_SEND);
                        rcmOut.setMessage(sms.toString());
                        rc.sendMessage("FS", "fsIN", rcmOut);
                    }
                    else if ( sms.getTextMessage().length() <= 12 ) {
                        
                        storeSMS.put(sms.getTextMessage(), sms);
                        
                        DrugQuery drugQuery = new DrugQuery(sms.getTextMessage(), Authenticity.NONE);
                    
                        RabbitClientMessage rcmOut = new RabbitClientMessage();
                        rcmOut.setMessageType(RabbitClientMessageType.QUERY_DRUG_VERIFY);
                        rcmOut.setMessage(drugQuery.toString());
                        rc.sendMessage("LS", "lsIN", rcmOut);
                    }                    
                } break;
                    
                case QUERY_DRUG_RESULT:
                {
                    DrugQuery drugQuery = new DrugQuery(message);
                    
                    SMS smsToReply = storeSMS.get(drugQuery.getUniqueID());
                    
                    String suppliedID = drugQuery.getUniqueID();
                    String recievingNumber = smsToReply.getSendingNumber();
                    
                    StringBuilder messageText = new StringBuilder();
                    messageText.append("Input ID = "+suppliedID);
                    messageText.append("\r\n");

                    if ( drugQuery.getAuthenticity() == Authenticity.AUTHENTIC ) {
                        messageText.append("Integrity = GENIUNE");
                    }
                    else {
                        messageText.append("Integrity = FAKE");
                    }
                    
                    messageText.append("\r\n");
                    messageText.append("Powered By = NAML");
                    
                    SMS sms = new SMS();
                    sms.setRecievingNumber(recievingNumber);
                    sms.setMessageText(messageText.toString());
                    
                    RabbitClientMessage rcmOut = new RabbitClientMessage();
                    rcmOut.setMessageType(RabbitClientMessageType.SMS_SEND);
                    rcmOut.setMessage(sms.toString());

                    rc.sendMessage("FS", "fsIN", rcmOut);
                    
                } break;
                
            }
        }        
        catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParseException {
        
        try {
            
            boolean isDebug = true;
            String propertyFileName = "";

            if ( args.length > 0 ) {
                propertyFileName = args[0];
                PropertyLoader.LOAD_RESOURCE_TYPE = PropertyLoader.LoadResourceType.URL;
            }
            
            ApplicationConfig appConf = ApplicationConfig.GetObject(propertyFileName);
            
            log.info("Initializing SMSC");
            
            SMSC smsc = new SMSC(appConf.getValue("hostname"));
            smsc.start();
            
            log.info("Started SMSC");
            
            while( true && !isDebug ) {

                String line = System.console().readLine();
                
                if( line.equalsIgnoreCase("EXIT") ) {
                    break;
                }                
            }
        }
        catch (IOException ex) {
            log.error(ex.getMessage());
        }
    }
}
